<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Notifications\EmailVerificationNotification;
use App\User;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Support\Facades\Cache;

class EmailVerificationController extends Controller
{
    public function send(Request $request){
        $user=$request->user();
        if($user->email_verified)
            throw new InvalidRequestException('你已经验证过邮箱了');
        $user->notify(new EmailVerificationNotification());
        return view('pages.success', ['msg'=>'邮件发送成功']);
    }
    public function verify(Request $request){
        $email=$request->get('email');
        $token=$request->get('token');
        if(!$email || !$token)
            throw new InvalidRequestException('验证链接不正确');
        if($token!=Cache::get('email_verification_'.$email))
            throw new InvalidRequestException('验证链接不正确或已过期');
        if(!$user= User::where('email', $email)->first())
            throw new InvalidRequestException('用户不存在');

        $user->update(['email_verified'=>true]);    // User 模型的 $fillable 需要添加字段 'email_verified' ！
        Cache::forget('email_verification_'.$email);

        return view('pages.success',['msg'=>'邮箱验证成功']);
    }
}
